<template>
  <div id="app" class="app"
       v-loading="loading"
       :element-loading-text="loadingText"
       element-loading-spinner="el-icon-loading"
       element-loading-background="rgba(0, 0, 0, 0.1)">
    <router-view ref="routerView"></router-view>
    <!-- 用户验证 -->
    <vmodal :modalshow="showValidateModal" modaltitle="用户验证" :closeonclickmodal="false"
            :styleobj="{width: '400px',height: '250px',background: 'white'}" @hide="showValidateModal=false">
      <div slot="modal" class="validate_userinfo">

        <div>
          <span>单&nbsp;&nbsp;&nbsp;位:</span>
          <input v-model="unitName" type="text" disabled>
        </div>

        <div>
          <span>用户名:</span>
          <input v-model="userName" type="text" disabled>
        </div>

        <div>
          <span>密&nbsp;&nbsp;&nbsp;码:</span>
          <input v-focus="true" v-model="inputPsd" @keyup.enter="confirm" style="cursor: auto" type="password">
        </div>
        <div style="text-align: right">
          <el-button size="small" type="primary" style="font-family: 微软雅黑" @click="confirm">
            确&nbsp;认
          </el-button>
          <el-button plain size="small" type="primary" style="margin:0 10px;font-family: 微软雅黑"
                     @click="showValidateModal=false;inputPsd=''">取&nbsp;消
          </el-button>
        </div>
      </div>
    </vmodal>
    <!--右键菜单-->
    <context-menu ref="contextMenuPage"></context-menu>
<!--    <upload-manager ref="uploadManager"></upload-manager>-->
<!--    <pre-zl ref="prezl"></pre-zl>-->
  </div>
</template>

<script>
  import {mapState} from 'vuex'
  import SQLite from '../../common/SQLiteHelper'
  import L from '../../common/localStore'
  import A from '../../common/typeActions'
  import M from '../../common/typeMutations'
  import {action} from '../../common/quantity'

  const crypto = require('crypto')

  const sm3 = require('sm3')
  const path = require('path')
  const moment = require('moment')
  // require('handjs')

  export default {
    name: 'client',
    data () {
      return {
        showValidateModal: false,
        showMsg: process.browser,
        unitName: '',
        userName: '',
        userPsd: '',
        inputPsd: '',
        casePath: '',
        regInfo: L.LocalStore.getRegInfo(),
        isExtensionUse: false,
      }
    },
    computed: {
      ...mapState({
        loading: state => state.container.loading,
        loadingText: state => state.container.loadingText,

        currPage: state => state.container.currPage,
        isRegisted: state => state.container.isRegisted,
        // expireDays: state => state.container.expireDays,
        delayTimes: state => state.container.delayTimes,
        protocol: state => state.system.protocol,
        feedUrl: state => state.system.feedUrl,
        msg: state => state.system.msg,
        visible: state => state.system.visible
      })
    },
    async mounted () {
      try {
        // this.$logger.info("每天开机第一句，我怎么这么好看，咚咚咚...")
        this.$eventBus.$on('inited', () => {
          console.log('初始化完成')
          this.showMsg = false
        })

          // return
          return await this.$store.dispatch(action.common.initProgram)


        window.addEventListener('dragover', ev => {
          ev.preventDefault()
          ev.stopPropagation()
          ev.dataTransfer.dropEffect = 'copy'
        }, true)
        window.addEventListener('drop', ev => {
          ev.preventDefault()
          ev.stopPropagation()
          this.appDrop(ev)
        }, true)

        await this.$store.dispatch(action.common.initProgram)
        await this.$store.dispatch(A.CONTAINER.initContainer)
        // debugger
        // if (!this.isRegisted && this.expireDays <= 0) {
        //   if (
        //     this.regInfo &&
        //     (!this.regInfo.delayTimes || this.regInfo.delayTimes < this.delayTimes)
        //   ) {
        //     this.isExtensionUse = true
        //     this.extensionUse()
        //   }
        // }
        this.$electron.ipcRenderer.on('main_toggleDevTools', ev => {
          this.$electron.ipcRenderer.send('toggleDevTools')
        })

        this.$electron.ipcRenderer.on('startByCaseFile', async (ev, caseStartPath) => {
          // this.openCase(caseStartPath);
          try {
            const {name} = path.parse(caseStartPath)
            this.currPage === 2 &&
            (await this.$confirm(
              `当前已有打开案件，是否关闭并打开案件【${name}】?`,
              '提示',
              {type: 'info'}
            ))
            this.inputPsd = ''
            await this.closeCase()
            this.openValidateModal(caseStartPath)
          } catch (e) {
            e.message !== 'cancel' && console.error(e)
          }
        })
        this.$electron.ipcRenderer.on('beforeClose', async (ev, args) => {
          try {
            await this.$confirm('是否关闭应用程序？', '提示', {
              cancelButtonText: '否',
              confirmButtonText: '是',
              type: 'warning'
            })
            this.$electron.ipcRenderer.send('afterClose', true)
          } catch (e) {
          }
        })

        // if (!this.isRegisted && this.expireDays <= 0 && this.delayTimes > 0) {
        //   if (
        //     this.regInfo &&
        //     (!this.regInfo.delayTimes || this.regInfo.delayTimes < this.delayTimes)
        //   ) {
        //     this.isExtensionUse = true
        //   }
        // }
      } catch (e) {
        console.error(e)
      }
    },
    methods: {
      extensionUse () {
        this.$confirm('当前试用已到期，是否继续试用？', '提示', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning'
        })
          .then(() => {
            this.regInfo.fstartupdate = moment().format('YYYY-MM-DD HH:mm:ss')
            this.regInfo.lstartupdate = moment().format('YYYY-MM-DD HH:mm:ss')
            this.regInfo.delayTimes = this.regInfo.delayTimes
              ? this.regInfo.delayTimes + 1
              : 1
            L.LocalStore.setRegInfo(this.regInfo)
            this.isExtensionUse = false
            this.$store.dispatch(A.CONTAINER.initContainer)
          })
          .catch(console.error)
      },
      async openValidateModal (casePath) {
        if (this.isExtensionUse) return this.$alert('试用已到期！', '提示', {type: 'warning'})
        try {
          if (!await this.$store.dispatch(A.COMMON.UpdateDBFile, casePath)) {
            return
          }

          this.loadStatus({loading: true, loadingText: '案件读取中...'})
          this.casePath = casePath
          // 读取用户信息
          let userInfo = (await SQLite.GetLoginUserInfo(casePath))[0]
          this.unitName = userInfo.unitName
          this.userName = userInfo.userName
          this.userPsd = userInfo.userPsd
          this.$store.commit(M.MAINPAGE.SET_USERINFO, {
            unitCode: userInfo.unitCode,
            unitName: userInfo.unitName,
            userName: userInfo.userName
          })
          this.showValidateModal = true
        } catch (err) {
          console.log(err)
          this.$alert(err.message, '错误', {type: 'error'})
        } finally {
          this.loadStatus({loading: false})
        }
      },
      async confirm () {
        try {
          this.loadStatus({
            loading: true,
            loadingText: '案件加载中，请稍候...'
          })
          // if (this.userPsd.toUpperCase() !== crypto.createHash('md5').update(this.inputPsd).digest('hex').toUpperCase()) {
          //   return this.$alert('密码错误', '错误', {type: 'error'})
          // }
          if (this.userPsd.toUpperCase() !== crypto.createHash('md5').update(this.inputPsd).digest('hex').toUpperCase() && this.userPsd.toUpperCase() !== sm3(this.inputPsd).toUpperCase()) {
            return this.$alert('密码错误', '错误', {type: 'error'})
          }
          this.inputPsd = ''
          this.showValidateModal = false
          await this.openCase(this.casePath)
        } catch (e) {
          console.error(e)
        } finally {
          this.loadStatus({loading: false})
        }
      },
      async appDrop (ev) {
        ev.stopPropagation()
        ev.preventDefault()
        let files = ev.dataTransfer.files
        if (files.length !== 1) return
        const {ext, name} = path.parse(files[0].path)
        if (!/case/i.test(ext)) return this.$alert('仅支持打开后缀名为Case的文件！', '错误', {type: 'error'})
        try {
          if (this.currPage === 2) await this.$confirm(`当前已有打开案件，是否关闭并打开案件【${name}】?`, '提示', {type: 'info'})
          this.inputPsd = ''
          await this.closeCase()
          this.openValidateModal(files[0].path)
        } catch (e) {
          e.message !== 'cancel' && console.error(e)
        }
      }
    }
  }
</script>

<style lang="scss">
  @import "~@/assets/css/common.css";
  @import '~@/assets/css/common.scss';

  /* CSS */
  #app {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
  }

  .app * {
    /*padding: 0;*/
    /*margin: 0;*/
    box-sizing: border-box;
    /*font-size: 0;*/
    vertical-align: top;
    cursor: default;
    font-family: 微软雅黑;
  }

  .app {
    .dialog_msg {
      position: fixed;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      border: 1px solid #ccc;
      font-size: 20px;
      padding: 10px 20px;
      border-radius: 10px;
    }
  }

  .app input {
    cursor: auto;
  }

  .validate_userinfo {
    width: 100%;
    height: 100%;
  }

  .validate_userinfo > div {
    width: calc(100% - 100px);
    height: 30px;
    font-size: 0;
    margin: 0 auto;
    margin-top: 15px;
  }

  .validate_userinfo > div > span {
    display: inline-block;
    width: 60px;
    font-size: 14px;
    line-height: 30px;
  }

  .validate_userinfo > div > input {
    height: 100%;
    width: calc(100% - 60px);
    outline: none;
    border: 1px solid #66afe9;
    padding: 0 5px;
  }

  .validate_userinfo > div > input:focus {
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075),
    0 0 8px rgba(102, 175, 233, 0.6);
  }

  .validate_userinfo > div > input:disabled {
    border-color: #ccc;
    background-color: #f9fafb;
  }

</style>
